package nl.hu.verbrandendephoenix.server;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import nl.hu.verbrandendephoenix.shared.Bid;

public class BidMethods {
	public static boolean bidAuction(int aID, double bid, String key, Connection con) {
		double currentBid = 0;
		int userID = 0;
		int credits = 0;

		try {
			Statement stmt = con.createStatement();

			//Controle of bod hoger is dan de huidige bod
			ResultSet rs = stmt.executeQuery("SELECT MAX(Price) FROM Bids WHERE AuctionID = " + aID);
			if(rs.next())
				currentBid = rs.getDouble("MAX(PRICE)");

			if(currentBid >= bid)
				return false;

			rs = stmt.executeQuery("SELECT UserID FROM Gebruiker WHERE Loginkey = '" + key + "'");
			if(rs.next())
				userID = rs.getInt("USERID");

			//Controle of gebruiker genoeg credits heeft
			rs = stmt.executeQuery("SELECT Credits FROM Gebruiker WHERE Loginkey = '" + key + "'");
			if(rs.next())
				credits = rs.getInt(1);

			if(credits < bid)
				return false;

			//Bod toevoegen
			rs = stmt.executeQuery("INSERT INTO Bids VALUES (1, " + userID + "," +aID + "," + bid + ", sysdate)");

			stmt.close();
			con.close();
		}
		catch(SQLException ex) {
			ex.printStackTrace();
		}
		return true;
	}

	public static Bid getLatestOffer(int aucID, Connection con) {
		Bid b = new Bid();
		try {
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT * FROM Bids WHERE AuctionID = " + aucID + " AND Price = (SELECT MAX(Price) FROM Bids WHERE AuctionID = " + aucID + ")");
			while (rs.next()) {
				b.setBidID(rs.getInt("BIDID"));
				b.setUserID(rs.getInt("USERID"));
				b.setAuctionID(aucID);
				b.setPrice(rs.getInt("PRICE"));
				b.setDate(rs.getDate("BIDDATE"));
			}
				
		} catch(SQLException sqle) {
			System.out.println("SQLException: " + sqle.getMessage());
			sqle.printStackTrace();
		}
		return b;
	}
	
	public static boolean checkForBid(int aucID, Connection con){
		
		try{
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT * FROM Bids WHERE AuctionID = " + aucID);
			if(!rs.next()){
				return false;
			}else{
				return true;
			}
			
		} catch(SQLException sqle) {
			System.out.println("SQLException: " + sqle.getMessage());
			sqle.printStackTrace();
		}
		return false;
	}
	
	public static ArrayList<Bid> getAllHighestBids(Connection con) {
		ArrayList<Bid> bids = new ArrayList<Bid>();
		try {
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT AuctionID, MAX(Price) FROM Bids GROUP BY AuctionID");
			while (rs.next()) {
				Bid b = new Bid();
				b.setAuctionID(rs.getInt("AUCTIONID"));
				b.setPrice(rs.getInt("MAX(PRICE)"));
				bids.add(b);
			}
		} catch(SQLException sqle) {
			System.out.println("SQLException: " + sqle.getMessage());
			sqle.printStackTrace();
		}
		return bids;
	}
}
